from bs4 import BeautifulSoup

class W3cBs4:
    Bs4=None
    def __init__(self,w3chtml,parser='lxml'):
        if self.Bs4==None:
            self.Bs4=BeautifulSoup(w3chtml,parser)
    def left_menu(self):
        """
            获取左边菜单栏目链接
        """
        nodes=self.Bs4.select('#course > ul>li')
        # node.
        # print(nodes,len(nodes))
        # 处理 返回的list
        if len(nodes)==0:
            return []
        left_menu_dic=[]
        for item in nodes:
            for child in item:
                left_menu_dic.append({
                    'menu_name':child.contents[0],
                    'menu_url' :child['href']
                })
        return   left_menu_dic

        pass
    def get_next_content(self):
        """
            获取菜单内容返回
        """
        nodes = self.Bs4.select('#maincontent > div')[2:]
        # print(nodes)
        # exit()

        knowledge=[]

        for item in nodes:
            # print(item)
            divlist = {
                'name': '',
                'subname': '',
                'example': '',
                'remark': '',
                'example1': '',
            }
            h2=item.find('h2')
            if h2 != None:
                divlist['name']=h2.contents[0]
            p=item.find('p')
            # print(p)
            if p !=None:
                p_list=[]
                for list in p.strings:
                    p_list.append(str(list).strip())

                divlist['subname']=''.join(p_list)


            h3 = item.find('h3')
            pre = item.find('pre')
            if h3 != None and pre!=None:
                divlist['example'] = ':'.join([h3.contents[0],pre.contents[0]])
            p_note=item.select('.note')

            if len(p_note) >0:
                divlist['remark']=p_note[0].contents[0].contents[0]+p_note[0].contents[1]
            ul = item.select('ul')
            ul_in=[]
            # print(ul)
            if len(ul)>0:

                # print(ul[0])
                for child in ul[0].strings:
                    ul_in.append(str(child).strip())

                # for child in ul[0].contents:
                #     ul_in.append(child.string)
                divlist['remark']=str(divlist['remark'])+';'.join(ul_in)
            if divlist['name']=='':
                continue
            knowledge.append(divlist)
        return knowledge

    def py_get_content(self):
        f =open('./js.html','rt')
        data=f.read()
        f.close()
        return data
        pass


if __name__ == '__main__':
    # test=W3cBs4(open('./js.html'))
    # print(test.left_menu())
    # test=W3cBs4(open('./iteration.html'))
    test=W3cBs4(open('./nextjs.html'))
    print(test.get_next_content())
    for i in  test.get_next_content():
        print(i)
    pass